import { getToken } from "~/composables/state";
import { API, ResponseCodeSuccess } from "~/models/apis/api";
import { HTTPMethod , type UniHttpRequestRecord, type UniHttpRequest, type UniHttpResponse} from "~/models/types/uniHttp";
// import { HTTPMethod, type UniHttpRequestRecord, type UniHttpRequest } from "~/models/types/http"

export default async <R>(record:UniHttpRequestRecord<R>,bodyArgs:object = {} ,headerArgs:object = {},
    success: (response: UniHttpResponse<R>) => void = () => {},
fail: (response: UniHttpResponse<R>) => void = () => {}
) => {
    let header = {};
    if(record.IsAuth) header = Object.assign({Authorization:`Bearer ${getToken()}`},headerArgs);
    else header = headerArgs;
    
    console.log(`向${record.URL}发起${record.Method}请求`)
    const requestResult = await $fetch<UniHttpResponse<R>>(API.BASE+record.URL,{
        method:record.Method == HTTPMethod.POST?"POST":"GET",
        headers:header,
        body:record.Method == HTTPMethod.POST?{args:bodyArgs}:{},
        params:record.Method == HTTPMethod.GET?bodyArgs:{}
    })
    if(requestResult.code == ResponseCodeSuccess) success(requestResult)
    else fail(requestResult);
    
    return requestResult;
}
